import { Mode } from './mode.js';
import { Compiler } from '../cli/utils/compiler.js';
import { Globals } from './globals.js';
import { logger } from './logger.js';
import p, { existsSync } from 'node:fs';
import e from 'node:path';
import { pathToFileURL } from 'node:url';

let S=null;const C=new Set;function A(){return Globals.getConfig()??S}function B(){return C}async function E(t="robo",c=!1){const i=await T(t);let n;return i?(n=await b(i,c),C.add(i),i.includes(e.sep+"config"+e.sep)&&(logger.debug("Scanning for plugin files..."),n.plugins=n.plugins??[],await D(i,c,(r,a,o)=>{const s=n.plugins?.findIndex(l=>l===r||l[0]===r);s!==-1&&n.plugins?.splice(s,1),n.plugins?.push([r,a]),C.add(o);}))):n={clientOptions:{intents:[]}},S=n,Globals.registerConfig(n),logger.debug("Loaded configuration file:",n),n}async function T(t="robo"){const c=[".ts",".mjs",".cjs",".json"],i=["config",".config"];for(const n of i){const r=e.join(process.cwd(),n);for(const a of c){let o=e.join(r,`${t}.${Mode.get()}${a}`);try{if(p.existsSync(o))return logger.debug("Found configuration file at",o),o}catch{}try{if(o=e.join(r,`${t}${a}`),p.existsSync(o))return logger.debug("Found configuration file at",o),o}catch{}}}return null}async function D(t,c,i){const n=e.join(e.dirname(t),"plugins");if(!p.existsSync(n))return;const r=p.readdirSync(n),a=[];for(const o of r){const s=e.join(n,o);if(p.statSync(s).isDirectory()){const l=p.readdirSync(s);for(const f of l){const d=e.join(s,f),m=e.relative(n,d).split("."),j="@"+m[0];let y;m.length>2&&(y=m[1]),a.push({mode:y,name:j,path:d});}}else {const f=e.relative(n,s).split("."),d=f[0];let u;f.length>2&&(u=f[1]),a.push({mode:u,name:d,path:s});}}await Promise.all(a.map(async o=>{if(!o.mode){const l=a.find(f=>f.mode===Mode.get()&&f.name===o.name);if(existsSync(l?.path))return}if(o.mode&&o.mode!==Mode.get())return;const s=await b(o.path,c);i(o.name,s,o.path);}));}async function b(t,c=!1){try{if(t.endsWith(".json")){const i=p.readFileSync(t,"utf8");return JSON.parse(i)??{}}else if(t.endsWith(".ts")){const i=e.dirname(t);c?(logger.debug("Compiling TypeScript config..."),await Compiler.buildCode({clean:!1,copyOther:!1,distDir:e.join(".robo",e.relative(process.cwd(),i)),distExt:".mjs",files:[t.replace(process.cwd(),"")],parallel:1,srcDir:i})):logger.debug("Loading existing TypeScript config..."),t=e.join(process.cwd(),".robo",i.replace(process.cwd(),""),e.basename(t).replace(/\.ts$/,".mjs"));const n=await import(pathToFileURL(t).toString());return n.default??n??{}}else {const i=await import(pathToFileURL(t).toString());return i.default??i??{}}}catch(i){return logger.error("Failed to load configuration file:",i,t),{}}}

export { A as getConfig, B as getConfigPaths, E as loadConfig, T as loadConfigPath };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=config.js.map